package org.pupil.router.Random;

import org.pupil.common.URL;
import org.pupil.router.LoadBalancer;
import org.pupil.router.LoadContext;

import java.util.List;
import java.util.Random;

/**
 * @Description: 负载均衡：随机获取服务
 * @Author: pupil
 * @Date: 2024/07/24 下午 3:36
 */
public class RandomLoadBalancer implements LoadBalancer {

    private final Random random = new Random();

    @Override
    public URL select(LoadContext loadContext) {
        List<URL> urls = loadContext.getUrls();
        int size = urls.size();
        if (size == 0) {
            return null;
        }
        // 只有 1 个服务，不用随机
        if (size == 1) {
            return urls.get(0);
        }
        return urls.get(random.nextInt(size));
    }
}
